package cn.xxm.strategy.pay.i18n.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * httprequest工具类
 *
 */
public class HttpServletRequestUtils {
	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String,Object> getParameterMap(HttpServletRequest request) {
	    // 参数Map
	    Map<String, String[]> properties = request.getParameterMap();
	    // 返回值Map
	    Map<String,Object> returnMap = new HashMap<String,Object>();
	    Iterator<Entry<String, String[]>> entries = properties.entrySet().iterator();
	    Entry entry;
	    String name = "";
	    String value = "";
	    while (entries.hasNext()) {
	        entry = entries.next();
	        name = (String) entry.getKey();
	        Object valueObj = entry.getValue();
	        if(null == valueObj){
	            value = "";
	        }else if(valueObj instanceof String[]){
	            String[] values = (String[])valueObj;
	            for(int i=0;i<values.length;i++){
	                value = values[i] + ",";
	            }
	            value = value.substring(0, value.length()-1);
	        }else{
	            value = valueObj.toString();
	        }
	        returnMap.put(name, value);
	    }
	    return returnMap;
	}
	
	/**
	 * 获取请求参数json string
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static String getRequestJsonStr(HttpServletRequest request) throws Exception {
		BufferedReader reader = null;
		StringBuffer requestBuffer = new StringBuffer();
        try {
			reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
			//读入流，并转换成字符串
			String readLine;
			while ((readLine = reader.readLine()) != null) {
			    requestBuffer.append(readLine).append("\n");
			}
		} catch (Exception e) {
			throw e;
		}finally {
			reader.close();
		}
        return requestBuffer.toString();
	}
	
	/**
	 * 获取请求参数值
	 * @param key
	 * @return
	 * @throws Exception 
	 */
	public static Object getAttribute(HttpServletRequest request,String key) throws Exception {
		String requestStr = getRequestJsonStr(request);
		if(StringUtils.isBlank(requestStr)) {
			return null;
		}
		JSONObject json =JSONObject.parseObject(requestStr);
		return json.get(key);
	}
	


}
